import React from 'react';
import { Button, Form, Input, Card, Space, message } from 'antd';
import { useNavigate, useLocation } from 'react-router-dom';
import {
  reqAddHospitalSet,
  reqEditHospitalSet,
} from '@api/hospital/hospitalSet';
import { IaddHospitalSetParams } from '@api/hospital/hospitalSet/model/hospitalSetTypes';

export default function AddOrUpdateHospitalSet() {
  const navigate = useNavigate();
  const state = useLocation().state as IaddHospitalSetParams;
  //console.log(state);

  //给表单元素赋值
  const [form] = Form.useForm();
  //如果state有数据则是修改，没有数据就是添加
  if (state) {
    //console.log(form);
    form.setFieldsValue(state);
  }

  const onFinish = async (values: any) => {
    //由于添加修改是同一个组件
    if (state) {
      //修改
      values.id = state.id;
      await reqEditHospitalSet(values);
    } else {
      //添加
      await reqAddHospitalSet(values);
      //添加成功后，提示用户，并回到医院设置界面
    }

    message.success(state ? '医院数据修改成功' : '医院数据添加成功');
    navigate(-1);
  };

  return (
    <Card>
      <Form
        form={form}
        labelCol={{ span: 2 }}
        wrapperCol={{ span: 20 }}
        onFinish={onFinish}
        autoComplete='off'
      >
        <Form.Item
          label='医院名称'
          name='hosname'
          rules={[{ required: true, message: '请填写医院名称' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label='医院编码'
          name='hoscode'
          rules={[{ required: true, message: '请填写医院编码' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label='api基础路径'
          name='apiUrl'
          rules={[{ required: true, message: '请填写api基础路径' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label='联系人名称'
          name='contactsName'
          rules={[{ required: true, message: '请填写联系人名称' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label='联系人手机'
          name='contactsPhone'
          rules={[
            {
              required: true,
              message: '请填写联系人手机号码',
              pattern: /^1[3-9]\d{9}$/,
            },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 2, span: 16 }}>
          <Space>
            <Button type='primary' htmlType='submit'>
              保存
            </Button>
            <Button
              type='default'
              onClick={() => {
                navigate(-1);
              }}
            >
              返回
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Card>
  );
}
